import { Middleware, MiddlewareContext } from '../../core/types';

export interface BaseOptions {
  method?: string;
  headers?: Record<string, string>;
}

export function base(
  options: BaseOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  }
): Middleware {
  return async (ctx: MiddlewareContext, next) => {
    // Merge headers from options into config
    ctx.config.headers = {
      ...options.headers,
      ...ctx.config.headers,
    };

    // Initialize request object and validate URL format
    try {
      new URL(ctx.config.url || '');
    } catch (error) {
      throw new Error(`Invalid URL format: ${ctx.config.url || 'undefined'}`);
    }

    const method = ctx.config.method || options.method;
    const hasBody = method !== 'GET' && method !== 'HEAD' && ctx.config.data;

    ctx.request = new Request(ctx.config.url as string, {
      method,
      headers: new Headers(ctx.config.headers),
      body: hasBody ? JSON.stringify(ctx.config.data) : undefined,
    });

    await next();

    // Basic response processing
    if (ctx.response) {
      ctx.response.config = ctx.config;
      ctx.response.request = ctx.request;
    }
  };
}
